Vue Js Convert Multiple Object into Array: Vue.js is a popular JavaScript framework for building user interfaces. One useful feature of the language is the Object.entries() method, which can be used to convert an object into an array of key-value pairs.
How can I convert multiple objects into an array in Vue.js?
This is a Vue.js code that creates a Vue instance with a data object containing two objects (obj1 and obj2) with some key-value pairs. The code then uses the mounted() method to convert these objects to arrays using Object.entries(), and then combines them into a single array using the spread operator.
The resulting array is stored in the data property called combinedArray. The code also uses a v-for directive to loop through the combinedArray and display its items as list items on the web page. Each list item displays the key and value of each item in the array.
Vue Js Convert Multiple Object into Array Example
<div id='app'>
<ul>
<li v-for="(item, index) in combinedArray" :key="index">{{ item[0] }}: {{ item[1] }}</li>
</ul>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data: {
obj1: { name: 'John', age: 30, role: 'frontend developer' },
obj2: { name: 'Jane', age: 25, role: 'backend developer' },
combinedArray: []
},
mounted() {
// Convert objects to arrays using Object.entries()
const arr1 = Object.entries(this.obj1);
const arr2 = Object.entries(this.obj2);
// Combine arrays into a single array
this.combinedArray = [...arr1, ...arr2];
}
});
</script>